package com.gnerv.pabu.basic.https.config;

import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

@Configuration
public class EurekaHttpsClientConfig {

    @Autowired
    private Environment env;

    @Bean
    public DiscoveryClient.DiscoveryClientOptionalArgs discoveryClientOptionalArgs() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
        EurekaJerseyClientImpl.EurekaJerseyClientBuilder builder = new EurekaJerseyClientImpl.EurekaJerseyClientBuilder();
        String serverSslKeystore = env.getProperty("server.ssl.key-store");
        if(!StringUtils.isEmpty(serverSslKeystore)){
            serverSslKeystore = serverSslKeystore.replace("classpath:", "");
        }
        String serverSslKeystorePassword = env.getProperty("server.ssl.key-store-password");
        String springApplicationName = env.getProperty("spring.application.name");
        String eurekaClientServiceUrl = env.getProperty("eureka.client.serviceUrl.defaultZone");
        if (StringUtils.isEmpty(springApplicationName)) {
            springApplicationName = "eureka-https-client";
        }
        builder.withClientName(springApplicationName);
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(
                        this.getClass().getClassLoader().getResource(serverSslKeystore), serverSslKeystorePassword.toCharArray()
                )
                .build();
        builder.withCustomSSL(sslContext);
        builder.withMaxTotalConnections(10);
        builder.withMaxConnectionsPerHost(10);
        DiscoveryClient.DiscoveryClientOptionalArgs args = new DiscoveryClient.DiscoveryClientOptionalArgs();
        args.setEurekaJerseyClient(builder.build());
        return args;
    }
}